package com.blvtphan.tipocketclubs.adapter;

import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.blvtphan.tipocketclubs.R;
import com.blvtphan.tipocketclubs.model.CacheBitmap;
import com.blvtphan.tipocketclubs.util.GeneralUtils;

public class PreviewAdapter extends BaseAdapter {

	private List<String> lstImageName;
	private Context context;
	private LayoutInflater inflater;
	private CacheImage mCache;

	public PreviewAdapter(Context context, List<String> lstImageName,
			CacheImage memoryCache) {
		inflater = LayoutInflater.from(context);
		this.context = context;
		this.lstImageName = lstImageName;
		this.mCache = memoryCache;
	}

	@Override
	public int getCount() {
		return lstImageName.size();
	}

	@Override
	public Object getItem(int arg0) {
		return lstImageName.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	@SuppressLint("NewApi")
	@Override
	public View getView(final int pos, View view, ViewGroup group) {
		// TODO Auto-generated method stub
		View v = view;
		final ViewHolder hoder;
		if (v == null) {
			v = inflater.inflate(R.layout.box_image_preview, group, false);
			v.setTag(R.id.img_preview, v.findViewById(R.id.img_preview));
			hoder = new ViewHolder();
			hoder.pic = (ImageView) v.findViewById(R.id.img_preview);
			v.setTag(hoder);
		} else {
			hoder = (ViewHolder) v.getTag();
		}

		AsyncTask<Void, Void, CacheBitmap> task = new AsyncTask<Void, Void, CacheBitmap>() {

			@Override
			protected CacheBitmap doInBackground(Void... params) {

				Bitmap tmp = mCache
						.getBitmapFromMemCache(lstImageName.get(pos));
				if (tmp != null) {
					CacheBitmap bt = new CacheBitmap();
					bt.setKey(lstImageName.get(pos));
					bt.setBitmap(tmp);
					Log.d("Using Image Memory Cache :", "FYI");
					return bt;
				} else {
					Log.d("Downloading Images :", "FYI");
					return GeneralUtils.downloadImageWithCache(context, lstImageName.get(pos));
				}
			}

			@Override
			protected void onPostExecute(CacheBitmap result) {
				if (result != null) {
					mCache.addBitmapToMemoryCache(result.getKey(),
							result.getBitmap());
					hoder.pic.setImageBitmap(result.getBitmap());
				}
			}
		};

		if (Build.VERSION.SDK_INT >= 11) {
			task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		} else {
			task.execute();
		}
		return v;
	}

	static class ViewHolder {
		ImageView pic;
	}

}
